<template>
  <div class="mobile-login-container">
    <!-- 顶部Logo -->
    <div class="logo-section">
      <div class="logo-wrapper">
        <img
            src="@/assets/login.png"
            alt="宠物世家"
            class="logo-image"
            @error="handleImageError"
        />
      </div>
      <h1 class="app-title">快快乐乐-宠物世家</h1>
    </div>

    <!-- 登录表单 -->
    <div class="form-section">
      <van-form @submit="submitLogin" ref="loginFormRef" class="login-form" :show-error-message="false">
        <!-- 用户名 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">用户名:</span>
            <van-field
                v-model="loginFormModel.username"
                name="username"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '请输入用户名' }]"
                clearable
                class="form-input"
                :class="{ 'input-error': errors.username }"
                @blur="validateField('username')"
            >
              <template #left-icon>
                <van-icon name="user-o" class="input-icon" />
              </template>
            </van-field>
          </div>
          <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
        </div>

        <!-- 密码 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">密码:</span>
            <van-field
                v-model="loginFormModel.password"
                type="password"
                name="password"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请输入密码' }]"
                clearable
                class="form-input"
                :class="{ 'input-error': errors.password }"
                @blur="validateField('password')"
            >
              <template #left-icon>
                <van-icon name="lock" class="input-icon" />
              </template>
            </van-field>
          </div>
          <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
        </div>

        <!-- 验证码 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">验证码:</span>
            <div class="captcha-container">
              <van-field
                  v-model="loginFormModel.captcha"
                  name="captcha"
                  placeholder="请输入验证码"
                  :rules="[{ required: true, message: '请输入验证码' }]"
                  class="form-input captcha-input"
                  :class="{ 'input-error': errors.captcha }"
                  @blur="validateField('captcha')"
              >
                <template #left-icon>
                  <van-icon name="comment-o" class="input-icon" />
                </template>
              </van-field>
              <div class="captcha-wrapper" @click="refreshCaptcha">
                <img
                    :src="captchaUrl"
                    class="captcha-image"
                    alt="验证码"
                />
                <div class="captcha-refresh">
                  <van-icon name="replay" size="12" />
                </div>
              </div>
            </div>
          </div>
          <div v-if="errors.captcha" class="error-message">{{ errors.captcha }}</div>
        </div>

        <!-- 登录按钮 - 单独一行 -->
        <div class="login-btn-wrapper">
          <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              :disabled="loading"
              loading-text="登录中..."
              class="login-btn"
          >
            <span v-if="!loading">登 录</span>
          </van-button>
        </div>
      </van-form>

      <!-- 辅助功能 -->
      <div class="helper-links">
        <span class="link-item" @click="goToRegister">立即注册</span>
        <span class="divider">|</span>
        <span class="link-item" @click="goToForget">忘记密码</span>
      </div>
    </div>

    <!-- 底部版权 -->
    <div class="footer">
      <p class="copyright">&copy; 2024 宠物世家 版权所有</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { showSuccessToast, showFailToast } from 'vant'
import { useRouter } from 'vue-router'
import { login } from '@/api/loginUser.js'
import { v4 as uuid } from 'uuid'
import { saveJwt } from '@/api/jwt.js'
import api from "@/util/api.js";

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref()

// 验证码相关
const captchaUrl = ref('')
const captchaId = ref('')

// 错误信息
const errors = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 登录表单数据
const loginFormModel = reactive({
  username: '15269478955',
  password: '234354',
  captcha: ''
})

// 处理图片加载失败
const handleImageError = (event) => {
  event.target.style.display = 'none'
  const parent = event.target.parentElement
  if (parent) {
    parent.innerHTML = '<div class="logo-placeholder">🐾</div>'
  }
}

// 初始化验证码
onMounted(() => {
  refreshCaptcha()
})

// 刷新验证码
function refreshCaptcha() {
  const id = uuid()
  captchaId.value = id
  captchaUrl.value = `/api/loginUser/captcha?id=${id}&t=${Date.now()}`
}

// 验证单个字段
function validateField(fieldName) {
  const value = loginFormModel[fieldName]

  switch (fieldName) {
    case 'username':
      errors.username = value ? '' : '用户名不能为空'
      break
    case 'password':
      errors.password = value ? '' : '密码不能为空'
      break
    case 'captcha':
      errors.captcha = value ? '' : '验证码不能为空'
      break
  }
}

// 验证所有字段
function validateAll() {
  validateField('username')
  validateField('password')
  validateField('captcha')

  return !errors.username && !errors.password && !errors.captcha
}

// 清除所有错误
function clearErrors() {
  errors.username = ''
  errors.password = ''
  errors.captcha = ''
}

// 提交登录
async function submitLogin() {
  try {
    loading.value = true
    clearErrors()

    // 先进行前端验证
    if (!validateAll()) {
      showFailToast('请完善表单信息')
      return
    }

    const formData = {
      ...loginFormModel,
      id: captchaId.value
    }

    const resp = await login(formData)

    if (resp?.success) {
      showSuccessToast('登录成功')
      saveJwt(resp.data)
      await router.push('/mobile/main')
    } else {
      showFailToast(resp?.msg || '登录失败，请重试')
      refreshCaptcha()
    }
  } catch (error) {
    console.error('登录错误:', error)
    showFailToast('网络错误，请检查连接')
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

async function goToRegister() {
  await router.push("/registry");
}

function goToForget() {
  showFailToast('找回密码功能开发中')
}
</script>

<style scoped>
.mobile-login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
  margin-top: 30px;
}

.logo-wrapper {
  margin-bottom: 15px;
}

.logo-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid rgba(255, 255, 255, 0.2);
}

.logo-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  border: 3px solid rgba(255, 255, 255, 0.2);
}

.app-title {
  color: white;
  font-size: 20px;
  margin: 0;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.form-section {
  background: transparent;
  padding: 0;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 25px;
  position: relative;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 4px;
}

.form-label {
  font-size: 16px;
  font-weight: 600;
  color: white;
  min-width: 60px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 透明输入框 - 完全显示背景 */
.form-input {
  flex: 1;
  background: transparent !important;
  border: 2px solid rgba(255, 255, 255, 0.5);
  border-radius: 10px;
  transition: all 0.3s ease;
}

.form-input :deep(.van-field__body) {
  background: transparent !important;
  padding: 12px 0;
}

.form-input :deep(.van-field__control) {
  color: white;
  font-size: 16px;
  background: transparent !important;
}

.form-input :deep(.van-field__control::placeholder) {
  color: rgba(255, 255, 255, 0.7);
}

.form-input :deep(.van-field__clear),
.form-input :deep(.van-field__show-password) {
  color: rgba(255, 255, 255, 0.8);
}

.form-input.input-error {
  border-color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1) !important;
}

.form-input.input-error :deep(.van-field__control) {
  color: #ff4d4f;
}

.input-icon {
  color: rgba(255, 255, 255, 0.8);
  margin-right: 8px;
}

/* 错误消息样式 */
.error-message {
  color: #ff4d4f;
  font-size: 13px;
  margin-top: 6px;
  padding: 0 12px;
  text-align: right;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  animation: shake 0.3s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}

/* 验证码容器 */
.captcha-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-wrapper {
  position: relative;
  cursor: pointer;
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.captcha-image {
  width: 100px;
  height: 44px;
  border-radius: 8px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  object-fit: contain; /* 确保图片完全显示 */
  background: rgba(255, 255, 255, 0.9); /* 白色背景确保验证码清晰 */
  transition: border-color 0.3s ease;
}

.captcha-wrapper:hover .captcha-image {
  border-color: #667eea;
}

.captcha-refresh {
  position: absolute;
  bottom: -6px;
  right: -6px;
  background: #667eea;
  color: white;
  border-radius: 50%;
  width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 登录按钮样式 - 单独一行 */
.login-btn-wrapper {
  margin: 35px 0 25px 0;
  width: 100%;
}

.login-btn {
  height: 55px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  font-size: 18px;
  font-weight: 600;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  width: 100%;
}

.login-btn:active {
  transform: translateY(2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.helper-links {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 25px;
}

.link-item {
  color: rgba(255, 255, 255, 0.9);
  font-size: 15px;
  cursor: pointer;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  transition: color 0.3s ease;
}

.link-item:hover {
  color: white;
}

.link-item:active {
  transform: scale(0.95);
}

.divider {
  color: rgba(255, 255, 255, 0.5);
}

.footer {
  text-align: center;
  margin-top: auto;
  padding: 25px 0;
}

.copyright {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
  margin: 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .mobile-login-container {
    padding: 15px;
  }

  .logo-image,
  .logo-placeholder {
    width: 70px;
    height: 70px;
  }

  .app-title {
    font-size: 18px;
  }

  .form-label {
    font-size: 15px;
    min-width: 55px;
  }

  .form-input :deep(.van-field__control) {
    font-size: 15px;
  }

  .captcha-image {
    width: 90px;
    height: 40px;
  }

  .login-btn {
    height: 50px;
    font-size: 16px;
  }

  .helper-links {
    gap: 15px;
  }

  .link-item {
    font-size: 14px;
  }
}

/* 移除van-field默认样式 */
:deep(.van-field__label),
:deep(.van-field__error-message) {
  display: none !important;
}

:deep(.van-cell-group) {
  background: transparent;
}
:deep(.van-cell-group::after) {
  display: none;
}

/* 确保输入框内部也是透明的 */
:deep(.van-field) {
  background: transparent !important;
}
</style>